package com.chexiehui.jc.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.SizeUtils;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.CommonAbsViewHolder;
import com.chexiehui.jc.adapter.CommonStickyListHeaderAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpFragment;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.CarPkListInfo;
import com.chexiehui.jc.model.PkLeLineModel;
import com.chexiehui.jc.model.PkRightChildModel;
import com.chexiehui.jc.mvp.car.CarBrandParameterCompareCovenant;
import com.chexiehui.jc.mvp.car.CarBrandParameterComparePresenter;
import com.chexiehui.jc.ui.activity.ChooseCarModelActivity;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.widget.CustomHScrollView;
import com.chexiehui.jc.widget.CustomStickyListHeadersListView;
import com.chexiehui.jc.widget.InterceptScrollLinearLayout;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 参数对比
 */

public class CarBrandParameterCompareFragment extends BaseMvpFragment<CarBrandParameterComparePresenter> implements CarBrandParameterCompareCovenant.View {


    @BindView(R.id.ll_head_container)
    LinearLayout llHeadContainer;
    @BindView(R.id.nsgv_title_grid)
    NonSlidingGridView nsgvTitleGrid;
    @BindView(R.id.chsv_title_scroller)
    CustomHScrollView chsvTitleScroller;
    @BindView(R.id.isll_title_intercept_container)
    InterceptScrollLinearLayout isllTitleInterceptContainer;
    @BindView(R.id.slhlv_content_list)
    CustomStickyListHeadersListView slhlvContentList;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    private List<CarInfo> compareList;
    private List<PkLeLineModel> contentListData;
    private CommonStickyListHeaderAdapter<PkLeLineModel> contentListAdapter;
    private List<CarPkListInfo> titleGridData;
    private CommonAdapter<CarPkListInfo> titleGridAdapter;

    public static CarBrandParameterCompareFragment getInstance(ArrayList<CarInfo> compareList) {
        CarBrandParameterCompareFragment fragment = new CarBrandParameterCompareFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("compareList", compareList);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_brand_parameter_compare;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            compareList = (ArrayList<CarInfo>) bundle.getSerializable("compareList");
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        if (compareList == null && compareList.size() < 1) {
            return;
        }
        titleGridData = new ArrayList<>();
        nsgvTitleGrid.setAdapter(titleGridAdapter = new CommonAdapter<CarPkListInfo>(mActivity, R.layout.item_car_pk_title_grid_car, titleGridData) {
            @Override
            protected void convert(ViewHolder viewHolder, CarPkListInfo item, int position) {
                viewHolder.setText(R.id.tv_item_name, item.getSpecName());
                viewHolder.getView(R.id.iv_item_delete).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        removePkItem(position);
                    }
                });
            }
        });

        contentListData = new ArrayList<>();
        contentListAdapter = new CommonStickyListHeaderAdapter<PkLeLineModel>(mActivity, R.layout.item_car_pk_left_header, R.layout.item_car_pk_parame_line, contentListData) {

            @Override
            protected void convertItem(CommonAbsViewHolder viewHolder, PkLeLineModel item, int position) {
                viewHolder.setText(R.id.tv_item_name, item.getParamName());
                NonSlidingGridView nsgv_item_grid = viewHolder.getView(R.id.nsgv_item_grid);
                nsgv_item_grid.setNumColumns(item.getChildList().size());
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgv_item_grid.getLayoutParams();
                lp.width = item.getChildList().size() * SizeUtils.dp2px(123);
                nsgv_item_grid.setLayoutParams(lp);
                nsgv_item_grid.setAdapter(new CommonAdapter<PkRightChildModel>(mActivity, R.layout.item_car_pk_right_params, item.getChildList()) {
                    @Override
                    protected void convert(ViewHolder childHolder, PkRightChildModel childItem, int childPosition) {
                        childHolder.setText(R.id.tv_item_value, childItem.getParamValue());
                    }
                });
                CustomHScrollView chsv_item_scroller = viewHolder.getView(R.id.chsv_item_scroller);
                chsvTitleScroller.addOnScrollChangedListener(new OnScrollChangedListenerImp(chsv_item_scroller));
            }

            @Override
            protected void convertHead(CommonAbsViewHolder viewHolder, PkLeLineModel item, int position) {
                viewHolder.setText(R.id.tv_item_titme, item.getGroupName());
            }
        };
        slhlvContentList.setAdapter(contentListAdapter);
        llHeadContainer.setFocusable(true);
        llHeadContainer.setClickable(true);
        llHeadContainer.setOnTouchListener(new MyTouchListener());
        slhlvContentList.setOnTouchListener(new MyTouchListener());
        mvpPresenter.getPkInfo();
    }

    private void removePkItem(int position) {
        compareList.remove(position);
        titleGridData.remove(position);
        contentListData.clear();
        chsvTitleScroller.removeAllOnScrollChangedListener();
        setTableData();
    }

    private void setTableData() {
        if (titleGridData.size() > 0) {
            for (int i = 0; i < titleGridData.get(0).getGroupParamsViewModelList().size(); i++) {
                for (int j = 0; j < titleGridData.get(0).getGroupParamsViewModelList().get(i).getParamList().size(); j++) {
                    contentListData.add(new PkLeLineModel(titleGridData.get(0).getGroupParamsViewModelList().get(i).getGroupName(), i,
                            titleGridData.get(0).getGroupParamsViewModelList().get(i).getParamList().get(j).getParamId(),
                            titleGridData.get(0).getGroupParamsViewModelList().get(i).getParamList().get(j).getParamName()));
                }
            }
            for (int i = 0; i < contentListData.size(); i++) {
                List<PkRightChildModel> list = new ArrayList<>();
                for (int j = 0; j < titleGridData.size(); j++) {
                    list.add(new PkRightChildModel(
                            titleGridData.get(j).getSpecId(),
                            titleGridData.get(j).getSpecName(),
                            titleGridData.get(j).getAllParamValue().get(i).getParamValue()));
                }
                contentListData.get(i).setChildList(list);
            }
        }
        nsgvTitleGrid.setNumColumns(titleGridData.size());
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvTitleGrid.getLayoutParams();
        lp.width = compareList.size() * SizeUtils.dp2px(123);
        nsgvTitleGrid.setLayoutParams(lp);
        titleGridAdapter.notifyDataSetChanged();
        contentListAdapter.notifyDataSetChanged();
    }

    class MyTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            //当在表头和listView控件上touch时，将事件分发给 ScrollView
            chsvTitleScroller.onTouchEvent(arg1);
            return false;
        }
    }

    class OnScrollChangedListenerImp implements CustomHScrollView.OnScrollChangedListener {
        CustomHScrollView mScrollViewArg;

        public OnScrollChangedListenerImp(CustomHScrollView scrollViewar) {
            mScrollViewArg = scrollViewar;
        }

        @Override
        public void onScrollChanged(int l, int t, int oldl, int oldt) {
            mScrollViewArg.smoothScrollTo(l, t);
        }
    }

    ;

    @Override
    protected CarBrandParameterComparePresenter createPresenter() {
        return new CarBrandParameterComparePresenter(this);
    }

    @Override
    public void onGetPkInfoSuccess(BaseModel<List<CarPkListInfo>> successResult) {
        loadingLayout.setStatus(LoadingLayout.Success);
        titleGridData.clear();
        titleGridData.addAll(successResult.getData());
        contentListData.clear();
        setTableData();
    }

    @Override
    public void onGetPkInfoFailure(BaseModel<Object> failureResult) {
        loadingLayout.setStatus(LoadingLayout.Success);
    }

    @Override
    public String getCarIds() {
        if (compareList == null || compareList.size() < 1) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < compareList.size(); i++) {
            sb.append(compareList.get(i).getId());
            if (i != compareList.size() - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    @OnClick({R.id.rl_add_container})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_add_container:
                mActivity.startActivityForResult(ChooseCarModelActivity.class, 200);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 200:
                if (resultCode == -1) {
                    if (data != null) {
                        CarInfo carInfo = (CarInfo) data.getSerializableExtra("carInfo");
                        if (carInfo != null) {
                            compareList.add(carInfo);
                            titleGridData.clear();
                            contentListData.clear();
                            titleGridAdapter.notifyDataSetChanged();
                            contentListAdapter.notifyDataSetChanged();
                            loadingLayout.setStatus(LoadingLayout.Loading);
                            mvpPresenter.getPkInfo();
                        }
                    }
                }
                break;
        }
    }
}
